package 阻塞队列案例;

/*class MyBlockQueue {
    private int[] array = new int[3];//队列容量
    private int head = 0;//对头指针
    private int tail = 0;//队尾指针
    private int size = 0;

    //放入元素
    public void put(int key) throws InterruptedException {
        //过载
        synchronized(this){
            //过量
            //用while 检测的原因是，有可能有多个线程操作，一个线程判满
            //另外两个个线程一个取出元素，一个又放入元素，这时，一个if就不够了，因为再次检测的时候，还是满的
            while(size >= array.length) {
                //阻塞等待到拿出元素
                this.wait();
            }
            array[tail] = key;
            tail++;
            if(tail >= array.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    //取出元素
    public int take() throws InterruptedException {
        //加锁，保证这套操作是原子的
        synchronized(this){
            while(array.length == 0){
                //阻塞等待到存入元素
                this.wait();
            }
            int ret = array[head];
            head++;
            if(head >= array.length){
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class Test2 {
    public static void main(String[] args){
        MyBlockQueue myBlockQueue = new MyBlockQueue();
        //2个线程往里放入元素
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 10; i++){
                    try {
                        myBlockQueue.put(i);
                        System.out.println("线程" + Thread.currentThread().getName() + "放入元素:" + i );
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 10; i < 20; i++){
                    try {
                        myBlockQueue.put(i);
                        System.out.println("线程" + Thread.currentThread().getName() + "放入元素:" + i );
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t2.start();
        //1个线程往外取出元素
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 20; i++){
                    try {
                        myBlockQueue.take();
                        System.out.println("线程" + Thread.currentThread().getName() + "取出元素:" + i);
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t3.start();
    }
}*/
